<script lang="tsx">
import useRender from "@/utils/hooks/render";
import Taro from "@tarojs/taro";
import { eventCenter, getCurrentInstance } from "@tarojs/taro";
import { defineComponent, onMounted, reactive, ref, useCssModule } from "vue";
import InfiniteLoading from "../InfiniteLoading/index.vue";

export type RequestParams = {
  currPage: number;
  pageSize: number;
};
export type NoDataCB = () => void;

// export type RequestArgs = [RequestParams, NoDataCB];

const ProList = defineComponent({
  props: {
    request: {
      type: Function as unknown as () => (
        params: RequestParams,
        cb: NoDataCB
      ) => Promise<any>,
      required: true,
    },
    pageSize: {
      type: Number,
      default: 20,
    },
  },
  setup(props, ctx) {
    const style = useCssModule();

    const items = ref<any[]>([] as any[]);
    const hasMore = ref(true);
    const reqArgs = reactive<[RequestParams, NoDataCB]>([
      {
        currPage: 1,
        pageSize: props.pageSize,
      },
      () => {
        hasMore.value = false;
      },
    ]);

    const loadMore = async (done) => {
      console.log("loadMore");

      reqArgs[0].currPage++;
      const data = await props.request(...reqArgs);
      items.value = [...items.value, ...data];
      done?.();
    };

    const onRefresh = async (done?: () => void) => {
      reqArgs[0].currPage = 1;
      items.value = await props.request(...reqArgs);

      done?.();
    };

    const firstRequest = async () => {
      Taro.showToast({
        title: "加载中",
        icon: "loading",
        mask: true,
        duration: 99999,
      });
      try {
        onRefresh();
        Taro.hideToast();
      } catch (error) {}
    };

    onMounted(() => {
      eventCenter.once(getCurrentInstance().router?.onShow, async () => {
        firstRequest();
      });
    });

    useRender(() => (
      <div class={style["pro-list"]}>
        <InfiniteLoading
          has-more={hasMore.value}
          onLoad-more={loadMore}
          onRefresh={onRefresh}
        >
          {items.value.map(
            (
              ...args //
            ) => ctx.slots.default?.(...args)
          )}
        </InfiniteLoading>
      </div>
    ));

    ctx.expose({ onRefresh, loadMore, firstRequest, items });
    return { onRefresh, loadMore, firstRequest, items };
  },
});

export default ProList;
</script>

<style lang="scss" module>
.pro-list {
  height: 100%;
  overflow-y: auto;
}
</style>
